package com.aiwiown.snackmq.broker.handler.console;

import com.aiwiown.snackmq.broker.auth.AuthorizationService;
import com.aiwiown.snackmq.cluster.metadata.MetadataManager;
import com.aiwiown.snackmq.common.handler.RequestContext;
import com.aiwiown.snackmq.common.message.Message;
import com.aiwiown.snackmq.common.message.MessageStatus;
import com.aiwiown.snackmq.common.message.MessageType;
import lombok.extern.slf4j.Slf4j;

/**
 * 【新增】处理控制台绑定队列到交换机请求的处理器。
 */
@Slf4j
public class BindQueueHandler extends AbstractLeaderRequiredConsoleHandler {

    public BindQueueHandler(MetadataManager metadataManager, AuthorizationService authorizationService) {
        super(metadataManager, authorizationService);
    }

    @Override
    public MessageType getMessageType() {
        return MessageType.BIND_QUEUE_REQUEST;
    }

    @Override
    protected void doHandle(RequestContext ctx, Message request) {
        try {
            String exchangeName = request.getProperty("exchangeName");
            String queueName = request.getTopic();
            String routingKey = request.getProperty("routingKey");

            if (exchangeName == null || queueName == null || routingKey == null) {
                throw new IllegalArgumentException("ExchangeName, Topic/QueueName, and RoutingKey properties are required.");
            }

            metadataManager.bindQueue(queueName, exchangeName, routingKey, status -> {
                Message response = Message.builder().type(MessageType.RESPONSE).messageId(request.getMessageId()).build();
                if (status.isOk()) {
                    response = response.toBuilder().status(MessageStatus.SUCCESS).build();
                } else {
                    log.error("Failed to bind queue via Raft: {}", status.getErrorMsg());
                    response = response.toBuilder().status(MessageStatus.FAILED).errorMessage(status.getErrorMsg()).build();
                }
                ctx.writeResponse(response);
            });
        } catch (Exception e) {
            log.error("Error processing bind queue request", e);
            Message response = Message.builder().type(MessageType.RESPONSE).messageId(request.getMessageId()).status(MessageStatus.FAILED).errorMessage("Internal server error: " + e.getMessage()).build();
            ctx.writeResponse(response);
        }
    }
}